class AddHTMLWebpackPlugin {
  constructor(options) {
    console.log('run AddHTMLWebpackPlugin')
    this.options = options
  }

  apply(compiler) {
    compiler.hooks.emit.tapAsync(
      'AddHTMLWebpackPlugin',
      (compilation, cb) => {
        let scripts = []
        Object.keys(compilation.assets).forEach(file => {
          if (file.endsWith('.js')) {
            scripts.push(`<script src="${file}"></script>`)
          }
        })
        compilation.assets[this.options.name || 'index.html'] = {
          source: function() {
            return `<html>${scripts.join('')}</html>`
          },
          size: function() {
            return this.source().length
          }
        }
        cb()
      }
    )
  }
}

module.exports = AddHTMLWebpackPlugin